<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="经验分享,">










<meta name="description" content="今天介绍个非常实用也非常好用的工具——NLog,这应该是.net环境下，普遍认为效率最高，功能最强，使用起来也最方便的日志类工具了，我们新上的系统日志类工具就是用的NLog,算起来我写了也就不到20行代码吧，就让我们的系统有了非常丰富的日志记录功能。NLog是一个开源插件，地址是http://nlog-project.org/，英文好的同学可以仔细去读读人家的文档，我先飘过~由于使用非常简单方便，">
<meta name="keywords" content="经验分享">
<meta property="og:type" content="article">
<meta property="og:title" content="记录系统日志的利器-NLog">
<meta property="og:url" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="今天介绍个非常实用也非常好用的工具——NLog,这应该是.net环境下，普遍认为效率最高，功能最强，使用起来也最方便的日志类工具了，我们新上的系统日志类工具就是用的NLog,算起来我写了也就不到20行代码吧，就让我们的系统有了非常丰富的日志记录功能。NLog是一个开源插件，地址是http://nlog-project.org/，英文好的同学可以仔细去读读人家的文档，我先飘过~由于使用非常简单方便，">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/NLogPackage.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/targets.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/rules.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/logs.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/test.png">
<meta property="og:updated_time" content="2018-08-24T03:50:01.875Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="记录系统日志的利器-NLog">
<meta name="twitter:description" content="今天介绍个非常实用也非常好用的工具——NLog,这应该是.net环境下，普遍认为效率最高，功能最强，使用起来也最方便的日志类工具了，我们新上的系统日志类工具就是用的NLog,算起来我写了也就不到20行代码吧，就让我们的系统有了非常丰富的日志记录功能。NLog是一个开源插件，地址是http://nlog-project.org/，英文好的同学可以仔细去读读人家的文档，我先飘过~由于使用非常简单方便，">
<meta name="twitter:image" content="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/NLogPackage.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2018/08/23/记录系统日志的利器-NLog/">





  <title>记录系统日志的利器-NLog | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2018/08/23/记录系统日志的利器-NLog/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">记录系统日志的利器-NLog</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-23T17:41:48+08:00">
                2018-08-23
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>今天介绍个非常实用也非常好用的工具——NLog,这应该是.net环境下，普遍认为效率最高，功能最强，使用起来也最方便的日志类工具了，我们新上的系统日志类工具就是用的NLog,算起来我写了也就不到20行代码吧，就让我们的系统有了非常丰富的日志记录功能。<br>NLog是一个开源插件，地址是<a href="http://nlog-project.org/，英文好的同学可以仔细去读读人家的文档，我先飘过" target="_blank" rel="noopener">http://nlog-project.org/，英文好的同学可以仔细去读读人家的文档，我先飘过</a><del>~<br>由于使用非常简单方便，所以英语不好也没关系，我就我的体验跟大家分享下，肯定也不是非常完整了，因为我也只是用了NLog提供的功能的冰山一角，只是看到好东西就忍不住要分享（xianbai）分享（xianbai）<br>首先，在项目里添加NLog，添加方式有很多种，推荐采用Nuget包的方式<br><img src="NLogPackage.png" alt="NLog包"><br>下载如图两个文件，第二个可以不下载自己创建也行，嫌麻烦的话就都下载下来，稍加改动就可以<br>安装好后，先修改配置文件，注意NLog写日志的方式是异步的，所以性能很好，而且，它也支持把日志同步到文件，数据库等，因为我觉得日志这种东西，看你怎么看了，如果你做的系统每条数据都十分重要，多方的同步是很有必要的，我这里只介绍写到文件的方式，同步到数据库的方式各位自行百度吧</del><br>首选项，NLog的配置文件有几个比较关键的节点，其实对大多数人包括我来说，只要明白两个节点的意义就足够了<br>一个是targets节点，一个是rules节点<br><targets> - 定义日志的目标/输出,下级是<target><br><rules> - 定义日志的路由规则,下级是<logger><br><img src="targets.png" alt="NLog节点"><br><img src="rules.png" alt="NLog节点"><br><targets>标签<br><target>区域定义了日志的目标或者说输出 ，,在这里可以按需设置文件名称和格式，输出方式。<br>name：自定义该target的名字,可供rule规则里使用<br>type： 定义类型,官方提供的可选类型有:<br>Chainsaw|ColoredConsole |Console |Database|Debug|Debugger|EventLog|File|LogReceiverService|Mail|Memory|MethodCall|Network |NLogViewer|Null |OutputDebugString|PerfCounter|Trace|WebService<br>不过常用的还是 File \Database \Colored Console\ Mail<br>layouts 用来规定布局样式,语法“${属性}”,可以把上下文信息插入到日志中，官方提供的可以用的属性见文末附录<br><rules>标签<br>各种规则配置在logger里<br>name - 记录者的名字<br>minlevel - 最低级别<br>maxlevel - 最高级别<br>level - 单一日志级别<br>levels - 一系列日志级别，由逗号分隔。<br>writeTo - 规则匹配时日志应该被写入的一系列目标，由逗号分隔。<br>对了这个配置文件里定义的变量，或者叫变量标签是<variable>,可以把一些存储路径什么的放在里面，然后在target里调用</variable></rules></target></targets></logger></rules></target></targets></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;variable name=&quot;variable1&quot; value=&quot;$&#123;basedir&#125;/logs&quot;/&gt;</span><br><span class="line"> &lt;targets&gt;   </span><br><span class="line">    &lt;target name=&quot;File&quot; xsi:type=&quot;File&quot; fileName=&quot;$&#123;variable1&#125;/$&#123;shortdate&#125;.txt&quot;/&gt;  </span><br><span class="line"> &lt;/targets&gt;</span><br></pre></td></tr></table></figure>

<p>配置文件整明白后，就可以上代码了<br>这里由于业务需要我在所有有输出的地方都打上了日志<br>各位可以根据自己实际所需，指哪打哪就行了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">using NLog;</span><br><span class="line">namespace YMcms.Common</span><br><span class="line">&#123;</span><br><span class="line">    public class Response</span><br><span class="line">    &#123;</span><br><span class="line">        private Logger logger = LogManager.GetCurrentClassLogger();</span><br><span class="line">        private string _message = &quot;&quot;;</span><br><span class="line">        /// &lt;summary&gt;</span><br><span class="line">        /// 返回代码. 0-失败，1-成功，其他-具体见方法返回值说明</span><br><span class="line">        /// &lt;/summary&gt;        </span><br><span class="line">        public int code &#123; get; set; &#125;</span><br><span class="line">        /// &lt;summary&gt;</span><br><span class="line">        /// 返回消息</span><br><span class="line">        /// &lt;/summary&gt;</span><br><span class="line">        public string message</span><br><span class="line">        &#123;</span><br><span class="line">            set</span><br><span class="line">            &#123;</span><br><span class="line">                _message = value;</span><br><span class="line">                if (code &gt; 0)</span><br><span class="line">                    logger.Info(_message);</span><br><span class="line">                else if (code == -1)</span><br><span class="line">                &#123;</span><br><span class="line">                    logger.Error(_message);</span><br><span class="line">                &#125;</span><br><span class="line">                else</span><br><span class="line">                &#123;</span><br><span class="line">                    logger.Warn(_message);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            get</span><br><span class="line">            &#123;</span><br><span class="line">                return _message;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        /// &lt;summary&gt;</span><br><span class="line">        /// 返回数据</span><br><span class="line">        /// &lt;/summary&gt;</span><br><span class="line">        public dynamic data &#123; get; set; &#125;</span><br><span class="line">        public Response()</span><br><span class="line">        &#123;</span><br><span class="line">            code = 0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后看一眼效果<br><img src="logs.png" alt="效果"><br><img src="test.png" alt="效果"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/经验分享/" rel="tag"># 经验分享</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2018/08/20/webapi集成第三方登陆/" rel="next" title="webapi集成第三方登陆，支付">
                <i class="fa fa-chevron-left"></i> webapi集成第三方登陆，支付
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2018/08/28/接口知识总结（转）/" rel="prev" title="接口知识总结（转）">
                接口知识总结（转） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
